<template>
  <el-popover
    placement="bottom-end"
    width="fit-content"
    :show-arrow="false"
    trigger="click"
    :visible="visible"
  >
    <div class="filter-content" style="min-width: 300px">
      <div
        class="check-item"
        v-for="(item, index) in selectedList"
        :key="index"
      >
        <el-checkbox v-model="item.selected" :label="item.label" size="large" />
        <div
          :style="{
            height: item.selected && ids.includes(item.id) ? '40px' : '0px',
            overflow: 'hidden',
            transition: 'height 0.3s ease 0s',
            paddingLeft: '20px',
          }"
        >
          文档格式：
          <el-select
            v-if="ids.includes(item.id)"
            v-model="item.originType"
            placeholder="选择"
            size="small"
            style="width: 180px"
          >
            <el-option
              v-for="op in handleOptions(item)"
              :key="op.value"
              :label="op.label"
              :value="op.value"
            />
          </el-select>
        </div>
      </div>
    </div>
    <div class="footer" style="width: 100%">
      <el-button round style="width: 145px" @click="visible = false"
        >取消
      </el-button>
      <el-button
        type="primary"
        :disabled="disabled"
        style="width: 145px"
        round
        @click="handleExport"
        >导出
      </el-button>
    </div>
    <template #reference>
      <el-button type="primary" round @click="visible = true">
        <el-icon class="el-icon--right" style="margin-right: 10px">
          <Download />
        </el-icon>
        导出
      </el-button>
    </template>
  </el-popover>
  <div class="mind-export">
    <course-mini-map
      ref="courseMindMap"
      m-key="courseMindMap"
      key="courseMindMap"
    />
  </div>
</template>
<script setup lang="ts">
import { ref, computed, inject } from 'vue'
import { exportToTxt } from '@/utils/tools'
import { asBlob } from 'html-docx-js-typescript'
import useCourseStore from '@/stores/course'
import { storeToRefs } from 'pinia'
import { httpGetContentByKey } from '@/api/course'
import CourseMiniMap from '@/views/course-analysis/components/CourseMiniMap.vue'
import { Download } from '@element-plus/icons-vue'
import type { PropType } from 'vue'

const courseStore = useCourseStore()
const { summarization, words, courseInfo, autoChapters, content, pdfURL } =
  storeToRefs(courseStore)
const props = defineProps({
  origin: {
    type: Array as PropType<any[]>,
    default: [],
  },
  fileName: {
    type: String,
    default: '',
  },
})
const courseMindMap = ref(null)
const visible = ref(false)
const ids = [1, 2, 3, 6]
const selectedList = ref([
  {
    label: '原文',
    value: 'origin',
    id: 1,
    selected: false,
    originType: 'docx',
  },
  {
    label: '导读',
    value: 'introduction',
    id: 2,
    selected: false,
    originType: 'docx',
  },
  {
    label: '改写',
    value: 'rewrite',
    id: 3,
    selected: false,
    originType: 'docx',
  },
  {
    label: 'PPT',
    value: 'ppt',
    id: 4,
    selected: false,
    originType: 'pptx',
  },
  {
    label: '视频',
    value: 'video',
    id: 5,
    selected: false,
  },
  {
    label: '脑图',
    value: 'mindmap',
    id: 6,
    selected: false,
    originType: 'xmind',
  },
  {
    label: '笔记',
    value: 'note',
    id: 7,
    selected: false,
  },
])

const disabled = computed(() => {
  return selectedList.value.every((item) => !item.selected)
})
const options = ref([
  {
    label: '.docx',
    value: 'docx',
  },
  {
    label: '.txt',
    value: 'txt',
  },
])
const mindmapOptions = ref([
  {
    label: '.xmind',
    value: 'xmind',
  },
  {
    label: '.png',
    value: 'png',
  },
  {
    label: '.svg',
    value: 'svg',
  },
  {
    label: '.pdf',
    value: 'pdf',
  },
])
const mapOptions = {
  origin: options.value, // 原文
  introduction: options.value, // 导读
  rewrite: options.value, // 改写
  // ppt: [],
  mindmap: mindmapOptions.value,
}
const handleOptions = (item: any) => {
  return mapOptions[item.value]
}
const exportToDocx = async (value: any, filename: string) => {
  const data: any = await asBlob(value, {
    orientation: 'portrait',
    margins: {
      top: 2160,
      right: 1440,
      bottom: 2160,
      left: 1440,
      header: 720,
      footer: 720,
      gutter: 0,
    },
  })
  let link = document.createElement('a')
  link.href = (URL || webkitURL).createObjectURL(data)
  link.setAttribute('download', filename + '.docx')
  link.click()
  link.remove()
}
const mapExportFn = {
  docx: exportToDocx,
  txt: exportToTxt,
}

const mindmap = async (item: any) => {
  if (courseMindMap.value) {
    courseMindMap.value.handleExport({
      type: item.originType,
      name: props.fileName + '_脑图',
    })
  } else {
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve('')
      }, 300)
    })
    await mindmap(item)
  }
}

const exportOrigin = (item) => {
  let content
  if (item.originType === 'docx') {
    content = props.origin.reduce((pre, next: any) => {
      return pre + `<p>${next.init}</p>`
    }, '')
  } else {
    content = props.origin.reduce((pre, next: any) => {
      return pre + `${next.init}\n`
    }, '')
  }
  return mapExportFn[item.originType](content, props.fileName + '_原文')
}
const exportIntroduce = (item) => {
  let html
  if (item.originType === 'docx') {
    let keyWord = words.value.reduce((pre, next) => {
      return pre + next + ' '
    }, '<h3>关键词</h3>')
    let article = autoChapters.value.reduce((pre, next: any) => {
      return pre + `<h4>${next.Headline}</h4><p>${next.Summary}</p>`
    }, '<h3>章节速览</h3>')
    let speakerSummary = summarization.value.ConversationalSummary.reduce(
      (pre, next: any) => {
        return pre + `<p>${next.Summary}</p>`
      },
      '<h3>发言人总结</h3>',
    )
    let question = summarization.value.QuestionsAnsweringSummary.reduce(
      (pre, next: any) => {
        return pre + `<h4>${next.Question}</h4><p>${next.Answer}</p>`
      },
      '<h3>要点回顾</h3>',
    )
    let summary = `<h3>全文概要</h3><p>${summarization.value.ParagraphSummary}</p>`
    let content = keyWord + summary + article + speakerSummary + question
    html = `<!DOCTYPE html><html lang="en"><body style="font-family:方正仿宋_GBK,serif;mso-ascii-font-family:'Times New Roman';">${content}</body></html>`
  } else {
    let keyWord = words.value.reduce((pre, next) => {
      return pre + next + ' '
    }, '关键词\n')
    let article = autoChapters.value.reduce((pre, next: any) => {
      return pre + `\n${next.Headline}\n${next.Summary}\n`
    }, '章节速览')
    let speakerSummary = summarization.value.ConversationalSummary.reduce(
      (pre, next: any) => {
        return pre + `\n${next.Summary}\n`
      },
      '发言人总结',
    )
    let question = summarization.value.QuestionsAnsweringSummary.reduce(
      (pre, next: any) => {
        return pre + `\n${next.Question}\n${next.Answer}\n`
      },
      '要点回顾',
    )
    let summary = `\n全文概要\n${summarization.value.ParagraphSummary}\n`
    html =
      keyWord +
      '\n' +
      summary +
      '\n' +
      article +
      '\n' +
      speakerSummary +
      '\n' +
      question
  }
  mapExportFn[item.originType](html, props.fileName + '_导读')
}
const getTranslate: Function = inject('handleTranslateFromAI')
const exportRewrite = async (item) => {
  let content
  if (!props.origin[0]?.aiTranslate) {
    await getTranslate()
  }
  if (item.originType === 'docx') {
    content = props.origin.reduce((pre, next: any) => {
      return pre + `<p>${next.aiTranslate}</p>`
    }, '')
  } else {
    content = props.origin.reduce((pre, next: any) => {
      return pre + `${next.aiTranslate}\n`
    }, '')
  }
  return mapExportFn[item.originType](content, props.fileName + '_改写')
}
const exportPpt = () => {
  if (pdfURL.value) {
    downloadLinkFile(pdfURL.value, props.fileName + '_PPT')
  } else {
    httpGetContentByKey({
      task_id: courseInfo.value.task_id,
      file_key: 'PptExtraction',
      id: courseInfo.value.id,
    }).then((res: any) => {
      downloadLinkFile(res.PdfPath, props.fileName + '_PPT')
    })
  }
}
function downloadLinkFile(url, fileName) {
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

const exportVideo = async () => {
  downloadLinkFile(courseInfo.value.file_url, props.fileName + '_视频')
}
const exportNote = () => {
  if (content.value) {
    exportToDocx(content.value, props.fileName)
    return
  } else {
    httpGetContentByKey({
      task_id: courseInfo.value.task_id,
      file_key: 'NotBook',
      id: courseInfo.value.id,
    }).then((res: any) => {
      exportToDocx(res.content, props.fileName + '_笔记')
    })
  }
}
const mapExport = {
  origin: exportOrigin,
  introduction: exportIntroduce,
  rewrite: exportRewrite,
  ppt: exportPpt,
  video: exportVideo,
  mindmap,
  note: exportNote,
}
const handleExport = () => {
  selectedList.value.forEach((item: any) => {
    if (item.selected) {
      mapExport[item.value](item)
    }
  })
  visible.value = false
}
</script>
<style lang="scss" scoped>
.mind-export {
  position: fixed;
  top: -1000px;
  left: -1000px;
  width: 800px;
  height: 800px;
  z-index: 100;
}
.filter-content {
  height: 280px;
  overflow-y: auto;
  overflow-x: hidden;
  @include scrollBar;
}

.check-item {
  min-height: 40px;
  display: flex;
  flex-direction: column;
}
</style>
